package service

import (
	"fmt"
	"go_web/config"
	"go_web/dao"
	"go_web/models"
	"html/template"
)

func GetPostsByCategoryID(cid, page, pageSize int) (*models.CategoryResponse, error) {
	//页面上涉及到的所有的数据，必须有定义
	categorys, err := dao.GetAllCategory()
	if err != nil {
		fmt.Println("GetAllCategory err")
		return nil, err
	}
	posts, err := dao.GetPostPageByCategoryId(cid, page, pageSize)
	if err != nil {
		fmt.Println("GetPostPage err")
		return nil, err
	}
	var postMores []models.PostMore

	for _, post := range posts {

		categoryName := dao.GetCategoryNameByID(post.CategoryId)
		userName := dao.GetUserNameByID(post.UserId)

		content := []rune(post.Content)
		if len(content) > 100 {
			content = content[0:100]
		}

		postMore := models.PostMore{
			Pid:          post.Pid,
			Title:        post.Title,
			Slug:         post.Slug,
			Content:      template.HTML(post.Content),
			CategoryId:   post.CategoryId,
			UserId:       post.UserId,
			CreateAt:     models.DateDay(post.CreateAt),
			UpdateAt:     models.DateDay(post.UpdateAt),
			ViewCount:    post.ViewCount,
			CategoryName: categoryName,
			UserName:     userName,
		}

		postMores = append(postMores, postMore)

	}

	if err != nil {
		return nil, err
	}

	// pages=(total -1)/pageSize+1
	total := dao.CountTotalPostPageByCategoryID(cid)
	pagesCount := (total-1)/pageSize + 1

	var pages []int

	for i := 0; i < pagesCount; i++ {
		pages = append(pages, i+1)
	}

	var hr = &models.HomeResponse{
		Viewer:    config.Cfg.Viewer,
		Categorys: categorys,
		Posts:     postMores,
		Total:     total,
		Page:      page,
		Pages:     pages,
		PageEnd:   page != pagesCount,
	}

	categoryName := dao.GetCategoryNameByID(cid)
	categoryResponse := &models.CategoryResponse{
		HomeResponse: hr,
		CategoryName: categoryName,
	}

	return categoryResponse, nil
}
